package cn.gzsxt.music.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.gzsxt.music.util.ConstantUtil;
import cn.gzsxt.music.util.PermissionUtil;

@Component
public class CheckLoginInterceptor implements HandlerInterceptor{
	//true 放行: false 拦截
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception{
		request.setCharacterEncoding("utf-8");
		System.out.println("--拦截器执行了--");
		//1.获取当前登录用户在Session中共享的信息
		Map<String, Object> admin = (Map<String, Object>)request.getSession().getAttribute(ConstantUtil.USER_IN_SESSION);
		System.out.println("登录用户信息: "+admin);
		if(admin == null) {
			//没有登录,跳转到登录页面,让其登录
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return false;
		}else {
			//获取uri
			String uri = request.getRequestURI();// 请求资源 = 上下文路径+资源名称
			//资源名称
			String servletPath = request.getServletPath();
			//去掉第一根斜杠
			servletPath = servletPath.substring(1);
			//判断用户的权限地址集合中是否包含请求地址 ,包含,放行. 不包含.拦截
			System.out.println(uri);
			System.out.println(servletPath);
			boolean flag = PermissionUtil.checkPermission(servletPath);
			//没有权限的,不放行,跳转到一个提示页面
			if(!flag) {
				response.sendRedirect(request.getContextPath()+"/noPermission.jsp");
			}
			return flag;
		}		
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
}
